const router = require("koa-router")();
const DB = require("../module/db");
const sd = require("silly-datetime");

router.get("/", async (ctx) => {
    ctx.body = "后台首页";

}).post("/addAtlas", async (ctx) => {
    let data = ctx.request.body;
    let list = {
        "name": data.name,
        "userId": data.userId,
        "mediaId": [],
        "intro": data.intro
    }
    let result1 = await DB.insert('atlas', list);
    let result2 = await DB.addArray("project", {"_id": DB.getObjectId(data.projectId)}, {"atlases": result1.ops[0]._id})
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    try {
        if (result1.result.ok && result2.result.ok) {
            // console.log(result1.ops[0]._id)
            ctx.body = {
                type: 1,
                info: result1.ops[0]._id
            };
            console.log(time + "：添加媒体集成功" + data.name);
        } else {
            ctx.body = {
                type: 0,
                info: "添加媒体集失败"
            };
        }
    } catch (e) {
        ctx.body = ctx.body = {
            type: 0,
            info: e
        };
        console.log(time + "：" + e);
    }

}).get("/getAtlases", async (ctx) => {
    let userId = ctx.query["userId"];
    let list = [];
    let imgList = [];
    // console.log(userId);
    let count = await DB.count('atlas', {"userId": userId});
    list.push(count);
    let names = await DB.findSomeCol('atlas', {"userId": userId}, {"name":1});
    list.push(names);
    let ids = await DB.findSomeCol('atlas', {"userId": userId}, {"_id":1});
    for (let i = 0 ; i < ids.length ; i++) {
        // console.log(ids[i]["_id"]);
        await DB.findOne('pictures', {"atlasId": ids[i]["_id"].toString()}).then((data, err) => {
            if (err)
                console.log(err);
            else {
                // console.log(data["imgBase64"]);
                imgList.push(data["imgBase64"]);
            }
        });
        // console.log(imgBase64);
    }
    list.push(imgList);
    ctx.body = list;
    // console.log(ctx.body);

}).post("/deleteAtlas", async (ctx) => {
    // console.log(ctx.request.body);
    let atlasId = ctx.request.body["id"];
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    let data1 = await DB.remove1('atlas', {"_id": DB.getObjectId(atlasId)});
    let data11 = await DB.deleteArray('project', {"_id": DB.getObjectId(ctx.request.body["projectId"])}, {"atlases": DB.getObjectId(atlasId)})
    if (data1.result.ok && data11.result.ok) {
        let data2 = await DB.findSomeCol('media', {"atlasId": atlasId}, {"_id": 1});
        let count = await DB.count('pictures', {"atlasId": atlasId});
        for (let i = 0; i < count; i++){
            let pictureId = data2[i]["_id"];
            let data3 = await DB.findSomeCol('pictures', {"_id": DB.getObjectId(pictureId)}, {"_id": 0, "fileId": 1});
            let fileId = data3[0]["fileId"];
            // console.log(pictureId);
            // console.log(data[0]["fileId"]);
            let data4 = await DB.remove1('pictures', {"_id": DB.getObjectId(pictureId)});
            if (data4.result.ok) {
                let data5 = await DB.remove1('fs.files', {"_id": DB.getObjectId(fileId)});
                let data6 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId)});
                if (data5.result.ok && data6.result.ok) {
                    let data7 = await DB.remove2('comment', {"pictureId": pictureId});
                    if (data7.result.ok) {
                        console.log(time + "：删除照片及其评论成功" + ctx.request.body["id"]);
                    } else {
                        ctx.body = 0;
                        console.log(time + "：删除照片成功，删除评论失败" + ctx.request.body["id"]);
                    }
                } else {
                    ctx.body = 0;
                    console.log(time + "：删除照片及其评论失败" + ctx.request.body["id"]);
                }
            } else {
                ctx.body = 0;
                console.log(time + "：删除照片及其评论失败" + ctx.request.body["id"]);
            }
        }
        ctx.body = 1;
        console.log(time + "：删除照片集成功" + ctx.request.body["id"]);
    } else {
        ctx.body = 0;
        console.log(time + "：删除照片集失败" + ctx.request.body["id"]);
    }

}).post("/getAtlases", async (ctx) => {
    let list = ctx.request.body.atlases
    let list2 = []
    for (let i = 0; i < list.length; i ++) {
        let data = await DB.find('atlas', {"_id": DB.getObjectId(list[i])})
        let count = await DB.count("media", {"mediaId": list[i]})
        let result = data[0]
        result.count = count
        list2.push(result)
    }
    ctx.body = list2;
});

module.exports = router.routes();